package com.wb.utils

import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.io.File

/**
 * 选择涩图
 *
 * @author 祁雪
 */
@Component
open class SelectImage {

    @Value("\${com.bot.image.girl.path}")
    open fun setGirlPath(path: String) {
        girlPath = path
    }

    @Value("\${com.bot.image.boy.path}")
    open fun setBoyPath(path: String) {
        boyPath = path
    }

    companion object {

        lateinit var boyPath: String

        lateinit var girlPath: String

        /**
         * 获取男性图片
         * @param num 数量 最大5
         * @return 返回图片绝对路径list
         */
        fun getBoyPics(num: Int?): ArrayList<File> {

            val paths = arrayListOf<File>()

            var number = if (num == null || num <= 0) 1
            else if (num > 5) 5 else num

            for (i in 0 until number) {
                val fileList = File(boyPath).listFiles()
                if (fileList.isNullOrEmpty()) {
                    number++
                    continue
                }

                val file = getFile(fileList[(Math.random() * fileList.size).toInt()].absolutePath)
                if (file == null) {
                    number++
                    continue
                }

                paths.add(file)
            }

            return paths
        }


        /**
         * 获取涩图
         * @param num 数量 最大5
         * @return 返回图片绝对路径list
         */
        fun getGirlPics(num: Int?): ArrayList<File> {

            val paths = arrayListOf<File>()

            var number = if (num == null || num <= 0) 1
            else if (num > 5) 5 else num

            for (i in 0 until number) {

                val fileList = File(girlPath).listFiles()
                if (fileList.isNullOrEmpty()) {
                    number++
                    continue
                }

                val file = getFile(fileList[(Math.random() * fileList.size).toInt()].absolutePath)
                if (file == null) {
                    number++
                    continue
                }
                paths.add(file)
            }

            return paths
        }

        fun getFile(path: String): File? {

            val file = File(path)
            if (file.exists()) {
                if (file.isDirectory) {
                    // 如果是文件夹 则列出文件随机选一个
                    val list = file.listFiles()

                    if (list == null || list.size == 0) {
                        return null
                    }

                    val filePath = list[(Math.random() * list.size).toInt()].absolutePath
                    return getFile(filePath)
                }
                return file
            }
            return null
        }

    }

}

fun main() {
    println(SelectImage.getFile("D:\\爬虫文件\\asian_to_lick")?.absolutePath)
}